//
//  SearchViewController.m
//  easystudy
//
//  Created by kane on 15/6/4.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultViewController.h"
@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    __weak IBOutlet UISearchBar *_searchBar;
    __weak IBOutlet UITableView *_searchTable;
    
    __weak IBOutlet UIButton *_cancleButton;
    __weak IBOutlet UIButton *_backButton;
    __weak IBOutlet UILabel *_selLineView;
    
    __weak IBOutlet UIView *resultView;
    __weak IBOutlet UIView *contentView;
    __weak IBOutlet UILabel *searchLabel;
    NSMutableArray *dataList;
    NSMutableArray *searchList;
    int iSearchType;
    
    
}

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    searchList = [[NSMutableArray alloc]initWithCapacity:0];
    dataList = [[NSMutableArray alloc] initWithObjects:@"苏联",@"商超",@"十字军",@"罗斯福",@"秦始皇",@"梁启超",@"周朝",@"明治维新", nil];
    
    [self initWithButtonWithNum:dataList.count];
    
    for (UIView *subView in _searchBar.subviews) {
        for (UIView *sub in subView.subviews) {
            if (![sub isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                [sub removeFromSuperview];
            }
        }
    }
//    resultView.hidden = YES;

}

- (void)initWithButtonWithNum:(NSInteger)num
{
    for (int i = 0; i < num; i ++) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(10+(i%2)*150, 150+(i/2)*45, 145, 40)];
        bgView.backgroundColor = KKColor_DarkGray_White;
        [contentView addSubview:bgView];
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(70, 5 , 50, 30)];
        [button setTitle:dataList[i] forState:UIControlStateNormal];
        [button setTitleColor:BlueColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
         button.tag = i + 100;
        [bgView addSubview:button];
    }
}

- (void)buttonClick:(id)sender
{
    SearchResultViewController *resultVC = [[SearchResultViewController alloc]initWithNibName:@"SearchResultViewController" bundle:nil];
    [self.navigationController pushViewController:resultVC animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchData
{
    [self.view endEditing:YES];
    
    NSString *province = @"0";
    NSString *city = @"0";
    if ([UserEntity sharedUser].AreaID) {
        //1:北京 795:上海 18:天津  2250:重庆
        int aid = [[UserEntity sharedUser].AreaID intValue];
        if (aid == 1 || aid == 795 || aid == 18 || aid == 2250) {
            province = [UserEntity sharedUser].AreaID;
        }else{
            city = [UserEntity sharedUser].AreaID;
        }
    }
    

}

#pragma mark - User Actions

- (IBAction)backBtnPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)orgBtnPressed:(id)sender {
 
}

- (IBAction)cancleBtnPressed:(id)sender {
   [UIView animateWithDuration:0.5 animations:^{
       _searchBar.frame = CGRectMake(75, 20, 170, 44);
       _cancleButton.hidden = YES;
       contentView.hidden = NO;
       resultView.hidden = YES;
       _backButton.hidden = NO;
       [_searchBar resignFirstResponder];
       _searchBar.text = @"";
       [searchList removeAllObjects];
       [_searchTable reloadData];
   }];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [UIView animateWithDuration:0.5 animations:^{
        _searchBar.frame = CGRectMake(15, 20, 245, 44);
        _cancleButton.hidden = NO;
        contentView.hidden = YES;
        _backButton.hidden = YES;
    }];
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self reloadSearchData:searchBar.text];
    [_searchTable reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length > 0) {
        resultView.hidden = NO;
        contentView.hidden = YES;
        [self reloadSearchData:searchText];
        [_searchTable reloadData];
    }
    else {
        resultView.hidden = YES;
        [searchList removeAllObjects];
        [_searchTable reloadData];
    }
}
- (void)reloadSearchData:(NSString *)text
{
    NSString *cityName = [UserEntity sharedUser].selectCity.length > 0 ? [UserEntity sharedUser].selectCity : [UserEntity sharedUser].CityName;
    NSString *code = [[Database sharedManager] queryCityCode:cityName];
    NSDictionary *param = @{@"pageNo":@"1",@"pageSize":@"20",@"city":code,@"search":text};
//    [WebService findHomeList:param WithBlock:^(id result, NSError *error) {
//        if (!error) {
//            [searchList removeAllObjects];
//            [searchList addObjectsFromArray:result[@"data"][@"dataList"]];
//            [_searchTable reloadData];
//        }else{
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
//        }
//    }];
}
#pragma mark - UITableView DataSource && Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return searchList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"HomeClassCell";
//    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    if (!cell) {
//        [tableView registerNib:[UINib nibWithNibName:@"HomeCell" bundle:nil] forCellReuseIdentifier:identifier];
//        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    }
//    NSDictionary *item = searchList[indexPath.row];
//    NSString *url = item[@"logo"] && [item[@"logo"] isKindOfClass:[NSString class]] ? item[@"logo"]  : @"";
////    [cell.logoIV setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"home_placeholder"]];
////    cell.nameLbl.text = item[@"name"];
////    cell.addressLbl.text = item[@"address"];
////    cell.addressLbl.frame = (CGRect){cell.addressLbl.origin,fWidth_Current - 20,20};
////    cell.addressLbl.numberOfLines = 2;
////    [cell.addressLbl sizeToFit];
   return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *item = searchList[indexPath.row];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchBar resignFirstResponder];
}
@end
